﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Autofac;
using Moq;
using Ue.CQRS.Bus;
using Ue.CQRS.Distributor;
using Ue.CQRS.Message;
using Ue.CQRS.Tests.Samples;
using Ue.CQRS.Tests.Samples.DataContracts;
using Ue.CQRS.Tests.Samples.Repositories;

namespace Ue.CQRS.Tests.Bus
{
    /// <summary>
    /// Bus 的摘要说明
    /// </summary>
    [TestClass]
    public class BusTests
    {
        private AppContext context;
        private IList<BookContract> bookContractCaches;

        [TestInitialize]
        public void Initial()
        {
            var mockBookReposiotry = new Mock<IBookRepository>();
            mockBookReposiotry.Setup(reposiotry => reposiotry.Save(It.IsAny<BookContract>()))
                .Callback<BookContract>(book => this.bookContractCaches.Add(book));

            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterInstance(mockBookReposiotry.Object);
            containerBuilder.RegisterType<DefaultDistributor>().As<IDistributor>();
            containerBuilder.RegisterType<DirectBus>().As<IBus>();

            this.context = new ApplicationContext(containerBuilder.Build());
        }

        [TestMethod]
        public void CreateBook()
        {
            var book = new BookContract()
            {
                Id=1,
                Title = "语文",
                Author = "成人教育出版社",
                Description = "成教大学一年级语文教科书",
                ISBN = "5863-5841368",
                Pages = 255
            };

            var bus = this.context.Resolve<IBus>();
            bus.Publish("CreateBookCommand",book);
            bus.Commit();

            Assert.AreEqual(1, bookContractCaches.Count);
            Assert.AreEqual(book, bookContractCaches[0]);
        }
    }
}
